package com.bluefuture.modules.app.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bluefuture.common.exception.GlobalException;
import com.bluefuture.common.utils.ResultEnum;
import com.bluefuture.common.utils.SendSmsUtil;
import com.bluefuture.modules.app.utils.CodeUtil;
import com.bluefuture.modules.app.utils.RedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: leo
 * @date: 2019/9/6
 */
@Service
@Slf4j
public class SmsService {

    @Autowired
    private RedisTemplate redisTemplate;

    public static void main(String[] args) {
        String verifyCode = "212312";
        String templateParas = "[\""+verifyCode+"\",\"30\"]";
        System.out.println(templateParas);
    }
    public void sendVerifyCode(String phoneNumber) {
        String smsCode = CodeUtil.getSmsCode();
        try {
            boolean result = SendSmsUtil.sendSms(phoneNumber, smsCode);
            if (!result){
                throw new GlobalException(ResultEnum.SMS_SEND_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("手机号：{}，验证码发送失败;错误信息：{}", phoneNumber, e.getCause());
            throw new GlobalException(ResultEnum.SMS_SEND_ERROR);
        }
        redisTemplate.opsForValue().set(RedisConstant.SMS_CODE_PREFIX + phoneNumber, smsCode, 30, TimeUnit.MINUTES);
    }

    public void sendVerifyCodeCopy(String phoneNumber) {
        String sendUrl = "http://smssh1.253.com/msg/variable/json";
        Map map = new HashMap();
        map.put("account", "N5455037");
        map.put("password", "7adLeP19iZ788c");
        map.put("msg", "【东客】您好，您的验证码为{$var},请不要把验证码泄露给其他人！{$var}分钟内有效。");
        String smsCode = CodeUtil.getSmsCode();
        int minutes = 30;
        String params = phoneNumber + "," + smsCode + "," + minutes;
        map.put("params", params);
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(map);
        String result = sendSmsByPost(sendUrl, jsonObject.toString());
        JSONObject resultJson = JSONObject.parseObject(result);
        String resultCode = resultJson.getString("code");
        if ("0".equals(resultCode)) {
            log.info("手机号：{}，验证码发送成功", phoneNumber);
        } else {
            log.error("手机号：{}，验证码发送失败;失败码：{};错误信息：{}", phoneNumber, resultCode, resultJson.getString("errorMsg"));
            throw new GlobalException(ResultEnum.SMS_SEND_ERROR);
        }
        redisTemplate.opsForValue().set(RedisConstant.SMS_CODE_PREFIX + phoneNumber, smsCode, 30, TimeUnit.MINUTES);
    }

    public void checkVerifyCode(String phoneNumber, String code) {
        String redisCode = (String) redisTemplate.opsForValue().get(RedisConstant.SMS_CODE_PREFIX + phoneNumber);
        if (redisCode == null || !redisCode.equals(code)) {
            throw new GlobalException(ResultEnum.SMS_CODE_ERROR);
        }
    }

    private String sendSmsByPost(String path, String postContent) {
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setConnectTimeout(10000);
            httpURLConnection.setReadTimeout(10000);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.connect();
            OutputStream os = httpURLConnection.getOutputStream();
            os.write(postContent.getBytes("UTF-8"));
            os.flush();
            StringBuilder sb = new StringBuilder();
            int httpRspCode = httpURLConnection.getResponseCode();
            if (httpRspCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
